package com.codingfly;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class ManticoreSearchService {

    public static int count = 0;
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public void testWrite() {
        long start = System.currentTimeMillis();
        deal(new File("/data/test-data-set/PixivNovel/"));
        long end = System.currentTimeMillis();
        logger.info("cost time   ===>>>   "+(end-start));
        logger.info(">>>>>>>>>>>>>>>>>>>>>finish<<<<<<<<<<<<<<<<<<<");
    }

    public void deal(File file) {
        if (file.isDirectory()) {
            for (File f:file.listFiles()) {
                deal(f);
            }
        } else {
            if (file.getName().endsWith(".txt") && file.getName().contains("-meta")==false) {
                String content = FileUtil.readString(file, "utf-8");
                String fileIndex = file.getName().replace(".txt", "");
                try {
                    // {"index":"testrt","id":1,"doc":{"title":"Hello","content":"world","gid":1}}
                    Long id = Long.valueOf(fileIndex);
                    Map<String, Object> bodyParams = new HashMap();
                    bodyParams.put("index", "t_article");
                    bodyParams.put("id", id);
                    Map<String, Object> docParams = new HashMap();
                    bodyParams.put("doc", docParams);
                    docParams.put("content", content);
                    long start = System.currentTimeMillis();
                    HttpResponse response = HttpRequest.of("http://localhost:9308/insert")
                            .body(JSON.toJSONString(bodyParams))
                            .method(Method.POST)
                            .execute();
                    long end = System.currentTimeMillis();
                    logger.info("one request cost time:" + (end - start) + "ms, http status code:" + response.getStatus() + " response:" + response.body());
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                count++;
                logger.info("deal file count:" + count);
            }
        }
    }

}
